﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows.Forms;

namespace Loki.UI.Win
{
    public static class BindingExtensions
    {
        public static void BindOneWay<TControl, TVM>(
            this TControl P_Control,
            Expression<Func<TControl, object>> P_Property,
            TVM P_Bindable,
            Expression<Func<TVM, object>> P_BindableProperty,
            IValueConverter P_Converter = null,
            object P_ValueConverterParameter = null)
            where TVM : INotifyPropertyChanged
            where TControl : Control
        {
            var L_Binder = FindBinder(P_Control);
            if (L_Binder != null)
            {
                L_Binder.OneWay<TControl, TVM>(P_Control, P_Property, P_Bindable, P_BindableProperty, P_Converter, P_ValueConverterParameter);
            }
        }

        public static void Bind<TControl, TVM>(
            this TControl P_Control,
            Expression<Func<TControl, object>> P_Property,
            TVM P_Bindable,
            Expression<Func<TVM, object>> P_BindableProperty,
            DataSourceUpdateMode P_Mode = DataSourceUpdateMode.OnValidation,
            IValueConverter P_Converter = null,
            object P_ValueConverterParameter = null)
            where TVM : INotifyPropertyChanged
            where TControl : Control
        {
            var L_Binder = FindBinder(P_Control);
            if (L_Binder != null)
            {
                L_Binder.TwoWay<TControl, TVM>(P_Control, P_Property, P_Bindable, P_BindableProperty, P_Mode, P_Converter, P_ValueConverterParameter);
            }
        }

        private static Databinder FindBinder<TControl>(TControl P_Form)
        {
            ViewBase L_BarForm = P_Form as ViewBase;
            if (L_BarForm != null)
            {
                return L_BarForm.DataBinder;
            }

            RibbonFormBase L_RibbonForm = P_Form as RibbonFormBase;
            if (L_RibbonForm != null)
            {
                return L_RibbonForm.DataBinder;
            }

            return null;
        }
    }
}
